package com.jzg.jcptadmin.presenter;

import com.jzg.jcptadmin.app.AppContext;
import com.jzg.jcptadmin.base.BasePresenter;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.local.ACache;
import com.jzg.jcptadmin.data.vo.StatusData;
import com.jzg.jcptadmin.viewinterface.StatusInterface;

import java.util.Map;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by jzg on 2016/1/6.
 */
public class StatusPresenter extends BasePresenter<StatusInterface> {
    private DataManager dataManager;
    private StatusInterface mView;
    private Subscription mSubscription;
    private AppContext appContext;

    public StatusPresenter(DataManager dataManager,AppContext appContext) {
        super();
        this.dataManager = dataManager;
        this.appContext = appContext;
    }

    @Override
    public void attachView(StatusInterface mvpView) {
        super.attachView(mvpView);
        this.mView = mvpView;
    }

    @Override
    public void detachView() {
        super.detachView();
        if (mSubscription != null) {
            mSubscription.unsubscribe();
            mView = null;
        }
    }

    public void LoadStatusData() {
        Map<String, String> params = mView.getLoadStatusParams();
        mSubscription = dataManager.loadStatus(params).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Observer<StatusData>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                if (e != null&&mView!=null) {
//                    mView.showError(Constant.errr_net);
                }
            }

            @Override
            public void onNext(StatusData statusData) {
                if (statusData.getStatus() == 100) {
                    savaStatus(appContext, statusData);
                }

            }
        });

    }

    /**
     * 保存状态
     *
     * @param appContext
     * @param statusData
     */
    public void savaStatus(AppContext appContext, StatusData statusData) {
        //appContext.setUser(user);
        ACache.get(appContext).put("statusData", statusData);
        detachView();
    }

}
